package cn.tedu.charging.device.startup;
import cn.tedu.charging.device.dao.repository.StationRepository;
import cn.tedu.charging.device.pojo.po.StationPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Slf4j
@Component
public class StationRunner implements ApplicationRunner {
    public static final String KEY_STATION_GEO = "stations_geo";
    private static final Object KEY_STATIONS_DETAIL = "stations_detail";
    @Autowired
    private StationRepository stationRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("启动数据加载预热");
       //1.从MySQL数据库获取充电站信息
        List<StationPO> stationPOList = stationRepository.selectStationList();
        log.debug("从数据库获取到的数据：{}",stationPOList);
        if(stationPOList==null||stationPOList.size()==0)return;
        //2.将充电站信息保存到Redis中
        //2.1基于此对象存储基础位置信息
        BoundGeoOperations boundGeoOperations = redisTemplate.boundGeoOps(KEY_STATION_GEO);
        //2.2基于此对象存储场站详情信息
        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(KEY_STATIONS_DETAIL);
        //2.3 循环遍历集合，将数据存储到Redis中
        for (StationPO stationPO : stationPOList) {
            //2.3.1 存储基础位置信息
            double lng = Double.valueOf(stationPO.getStationLng().toString());
            double lat = Double.valueOf(stationPO.getStationLat().toString());
            Point point=new Point(lng,lat);
            boundGeoOperations.add(point,String.valueOf(stationPO.getId()));
            //2.3.2 存储场站详情信息
            //System.out.println(stationPO);
            boundHashOperations.put(String.valueOf(stationPO.getId()),stationPO);
        }
        log.debug("数据预热完成");
    }
}
